# auto tapply function switch between single and multicore
# 
# Author: Guochun Shen
# Data:   2011-12-18
# Project:spatial statistic
# Email:  shenguochun@gmail.com
###############################################################################



auto_tapply=function(data,X,FUN, ...){
	types=unique(X)
	ntypes=length(types)
	#check global settings about parallel calculation
	if(PARALLEL){
		#avoid nested parallel calculation
		PARALLEL=FALSE;
		re=mclapply(1:ntypes,mtapply,data,X,types=types,fun=FUN,mc.cores=MC_CORES,...)
		PARALLEL=TRUE;
	}else{
		re=lapply(1:ntypes,mtapply,data,X,types=types,fun=FUN,...)
	}
	names(re)=types
	return(re)
}

mtapply=function(i,data,X,types,fun,...){
	subdata=data[X==types[i]]
	return(fun(subdata,...))
}
